/*
 * @Description: axios 封装
 * @Version: 1.0
 * @Autor: wq
 * @Date: 2021-08-04 14:28:21
 * @LastEditors: wq
 * @LastEditTime: 2021-08-05 08:45:23
 * @FilePath: \vue_project\mmpt\src\utils\request.js
 */

import axios from "axios";
import { Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,  // url = base url + request url
  timeout: 10000,
});

// 请求拦截
service.interceptors.request.use(
  (config) => {
    if (store.state.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 请求响应
service.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return Promise.resolve(response.data);
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          //   store.dispatch('user/resetToken').then(() => {
              Message({
                message: '登录信息失效,请重新登录！',
                type: 'error',
                duration: 1500,
                onClose: () => redirectLogin()
              })
          //   })
          break;
        case 500:
          Message({
            message: error.response.data.Message || "服务器异常，请稍后尝试",
            type: "error",
            duration: 2000,
          });
          break;

        default:
          return Promise.reject(error);
      }
    }
    return Promise.reject(error);
  }
);

// 跳转到登录
function redirectLogin() {
  router.push({
    name: "login",
    query: {
      redirect: router.currentRoute.fullPath,
    },
  });
}

export default service;
